<template>
  <div>
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible" width="940px" :modal="false">
      <div slot="title">
        <b v-if="!selectSku" class="def-b">{{ title }}</b>
        <b v-else class="def-b">请选择商品规格（{{ tempGoods.goodsName }}）</b>
      </div>
      <div v-show="!selectSku">
        <div v-loading="loading">
          <div class="form-seach">
            <el-form ref="form" :model="BindForm" label-width="80px" label-position="left">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="商品名称:" prop="commodityName" class="form-item">
                    <el-input v-model="BindForm.commodityName" placeholder="请输入商品名称" maxlength="30" class="cus-input" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品分类:" prop="type" class="form-item">
                    <select-goods-category v-model="BindForm.type" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品状态:" prop="commdityState" class="form-item">
                    <el-select v-model="BindForm.commdityState" clearable filterable placeholder="请选择商品状态" style="width: 100%">
                      <el-option value="0" label="未销售" />
                      <el-option value="1" label="销售中" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品类型:" prop="goodsType" class="form-item">
                    <el-select v-model="BindForm.goodsType" clearable filterable placeholder="请选择商品类型" style="width: 100%">
                      <el-option value="lease" label="租赁" />
                      <el-option value="sale" label="售卖" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item class="form-item">
                <el-button type="primary" @click="search">筛选</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div v-if="dialogVisible" class="ele-table">
            <el-table :data="BindTable" highlight-current-row border max-height="280" :empty-text="loading ? '数据加载中' : (isSearch ? '未找到相关的商品' : '暂无商品')" @row-click="select">
              <el-table-column
                label="商品编号"
                prop="goodsId"
                align="center"
                width="130"
                :resizable="false"
                fixed="left"
              />
              <el-table-column label="商品主图" align="center" :resizable="false" width="80">
                <template slot-scope="scope">
                  <TableColumnGoodsImage :src="scope.row.goodsImg" />
                </template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="goodsName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="商品类型"
                prop="type"
                align="center"
                width="90"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type == 'lease'" type="success" size="small">租赁</el-tag>
                  <el-tag v-else-if="scope.row.type == 'sale'" type="primary" size="small">售卖</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="商品状态"
                prop="state"
                align="center"
                width="90"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.state == 0" type="info" size="small">未销售</el-tag>
                  <el-tag v-else-if="scope.row.state == 1" type="success" size="small">销售中</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                header-align="center"
                align="center"
                fixed="right"
                width="100"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-button size="small" type="primary" @click="select(scope.row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination">
            <div />
            <el-pagination
              background
              :page-sizes="[10, 20, 30, 50, 100]"
              :page-size="limit"
              :pager-count="5"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="pageSizeChange"
              @current-change="currentPageChange"
            />
          </div>
        </div>
      </div>
      <div v-if="selectSku && tempGoods" style="padding: 0 30px">
        <el-form v-if="formData" ref="skuForm" :model="formData" label-width="300px" label-position="top">
          <el-form-item v-for="(skuItem, skuIndex) in tempGoods.skuList" :key="skuIndex" :rules="[{ required: true, message: '请选择' + skuItem.name, trigger: 'change' }]" :prop="'list.' + skuIndex + '.specId'" :label="skuItem.name">
            <el-radio-group v-model="formData.list[skuIndex].specId" @change="skuChange($event, skuIndex)">
              <el-radio v-for="(specItem, specIndex) in skuItem.specList" :key="specIndex" border :label="specItem.id">{{ specItem.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item style="margin-top: 30px; text-align: right">
            <el-button @click="back">上一步</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SelectGoodsCategory from '../SelectGoodsCategory/index'
import { commodityList } from '@/api/commodity'
import TableColumnGoodsImage from '../TableColumnGoodsImage/index'

export default {
  name: 'AddGoodsDialog',
  components: { TableColumnGoodsImage, SelectGoodsCategory },
  props: {
    title: {
      type: String,
      default: '请选择商品'
    },
    sku: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      page: 1,
      limit: 10,
      total: 0,
      loading: false,
      isSearch: false,
      BindForm: {
        commodityName: null,
        type: null,
        commdityState: null,
        goodsType: null
      },
      BindTable: [],
      tempGoods: null,
      selectSku: false,
      formData: null
    }
  },
  methods: {
    show() {
      this.tempGoods = null
      this.selectSku = false
      this.formData = null
      this.dialogVisible = true
      this.$nextTick(() => {
        this.resetForm()
      })
    },
    back() {
      this.tempGoods = null
      this.formData = null
      this.selectSku = false
    },
    resetForm() {
      const vm = this
      vm.$refs.form.resetFields()
      vm.reloadTableData()
    },
    search() {
      const vm = this
      vm.reloadTableData()
    },
    pageSizeChange(pageSize) {
      const vm = this

      vm.limit = pageSize

      vm.reloadTableData()
    },
    currentPageChange(page) {
      const vm = this

      vm.page = page

      vm.loadTableData()
    },
    reloadTableData() {
      const vm = this

      vm.page = 1
      vm.total = 0
      vm.BindTable = []
      vm.loadTableData()
    },
    loadTableData() {
      const vm = this

      vm.isSearch = false

      const data = {
        page: vm.page,
        limit: vm.limit
      }

      if (vm.sku) {
        data['hasSku'] = 1
      }

      if (vm.BindForm.commodityName && vm.BindForm.commodityName.length > 0) {
        data['commodityName'] = vm.BindForm.commodityName
        vm.isSearch = true
      }

      if (vm.BindForm.commdityState && vm.BindForm.commdityState.length > 0) {
        data['commdityState'] = parseInt(vm.BindForm.commdityState)
        vm.isSearch = true
      }

      if (vm.BindForm.goodsType && vm.BindForm.goodsType.length > 0) {
        data['goodsType'] = vm.BindForm.goodsType
        vm.isSearch = true
      }

      if (vm.BindForm.type && vm.BindForm.type.length > 0) {
        if (vm.BindForm.type && vm.BindForm.type.length === 2) {
          data['commdityType'] = vm.BindForm.type[0]
          data['commditySubType'] = vm.BindForm.type[1]
          vm.isSearch = true
        } else {
          data['commdityType'] = vm.BindForm.type[0]
          vm.isSearch = true
        }
      }

      vm.loading = true
      commodityList(data).then(res => {
        vm.loading = false
        vm.total = res.data.data.total
        vm.BindTable = res.data.data.list ? res.data.data.list : []
      }).catch(res => {
        vm.loading = false
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    select(val) {
      const vm = this

      vm.tempGoods = vm.$XEUtils.clone(val, true)
      vm.selectSku = false

      if (vm.tempGoods.skuList && vm.tempGoods.skuList.length > 0 && vm.sku) {
        vm.formData = {
          list: []
        }
        vm.tempGoods.skuList.forEach((skuItem, index) => {
          vm.formData.list.push({
            skuId: skuItem.skuId,
            skuName: skuItem.name,
            specId: null,
            specName: null
          })
        })

        vm.selectSku = true
      } else {
        vm.dialogVisible = false
        vm.$emit('select', vm.tempGoods)
      }
    },
    skuChange(val, skuIndex) {
      const vm = this

      vm.tempGoods.skuList[skuIndex].specList.forEach(specItem => {
        if (specItem.id === val) {
          vm.formData.list[skuIndex].specName = specItem.name
        }
      })
    },
    submitForm() {
      const vm = this

      vm.$refs.skuForm.validate((valid) => {
        if (valid) {
          vm.tempGoods.selectedSku = vm.$XEUtils.clone(vm.formData.list, true)
          const skuNames = []
          vm.tempGoods.selectedSku.forEach(item => {
            skuNames.push(item.skuName + '：' + item.specName)
          })
          vm.tempGoods.goodsSkuNames = skuNames.join('；')
          vm.dialogVisible = false
          vm.$emit('select', vm.tempGoods)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .def-b {
    border-left: 4px solid #3783ff;
    padding-left: 10px;
    word-break: break-all;
    width: calc(100% - 30px);
    display: flex;
    align-items: center;
  }

  .form-seach {
    padding: 20px 30px;
    padding-bottom: 0px;
    margin-bottom: 30px;
    border: 1px solid #eeeeee;

    .form-item {
      margin-bottom: 22px !important;
    }

  }

  .ele-table {
    margin-bottom: 30px;
  }
  .pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  ::v-deep.el-radio {
    margin-right: 15px !important;
  }
  ::v-deep.el-radio.is-bordered+.el-radio.is-bordered {
    margin-left: 0 !important;
    margin-bottom: 15px !important;
  }
</style>
